﻿/*
----------------------------------------------------------
* Company Name		: Worldsoft							
* Project Name		: RealState MVC 3.0							
* Object Name		: JsonFilterHelper.cs
* Description		: JSON Filter Attribute (JQuery to JSON - Ajax)		
* Programmer		: Nguyen Ngoc Manh
* Creation Date		: 26/11/2010		(dd/mm/yyyy)					
----------------------------------------------------------
 */
using System;
using System.Runtime.Serialization.Json;
using System.Web.Mvc;

namespace RealEstate.MVC.Web.Helper
{
    public class JsonFilter : ActionFilterAttribute
    {
        public string Param { get; set; }
        public Type JsonDataType { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
            {
                var jsonSerializer = new DataContractJsonSerializer(JsonDataType);
                var result = jsonSerializer.ReadObject(filterContext.HttpContext.Request.InputStream);
                filterContext.ActionParameters[Param] = result;
            }
            else
                throw new InvalidOperationException("Cannot use the JSON filter on this request as the content type is not marked as 'application/json'.");
        }
    }
}
